package com.example.content_provider_client;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.example.content_provider_client.entity.ImageInfo;
import com.example.content_provider_client.utils.FileUtil;
import com.example.content_provider_client.utils.PermissionUtil;
import com.example.content_provider_client.utils.ToastHelper;
import com.example.content_provider_client.utils.Utils;

import java.io.File;
import java.util.ArrayList;

public class ProviderMms extends AppCompatActivity {
    // 要申请的权限
    private static final String[] PERMISSIONS = new String[]{
            // Manifest.permission.READ_EXTERNAL_STORAGE,
            // 安卓17之后访问外部存储指定类型为图片-
            Manifest.permission.READ_MEDIA_IMAGES,
    };
    // 外部存储权限代码
    private static final int PERMISSION_CODE_STORAGE = 1;

    private ArrayList<ImageInfo> imageList = new ArrayList<>();
    private EditText etPhone;
    private EditText etTitle;
    private EditText etMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider_mms);

        etPhone = findViewById(R.id.et_phone);
        etTitle = findViewById(R.id.et_title);
        etMessage = findViewById(R.id.et_message);


        // 需要手动扫描MediaStorage库，更新外部存储的内容
        MediaScannerConnection.scanFile(this,
                new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()},
                null,
                null
        );

        // 检查权限
        boolean granted = PermissionUtil.checkPermission(this, PERMISSIONS, PERMISSION_CODE_STORAGE);
        Log.d("zhoutao", "onCreate: granted" + granted);
        if (granted) {
            // 读取图片
            loadImageList();
            // 加载图片
            showImageList();

//            // /storage/emulated/0/Download/pic5.jpg
//            // imgUri: content://media/picker_get_content/0/com.android.providers.media.photopicker/media/1000000034
//            ImageView imgTest = findViewById(R.id.iv_test);
//            // Uri uri = Uri.parse("/storage/emulated/0/Download/pic5.jpg");
//            Uri uri = Uri.parse("content://media/picker_get_content/0/com.android.providers.media.photopicker/media/1000000034");
//            imgTest.setImageURI(uri);
        }

    }

    // 把imageList中的图片添加到GridLinear中
    private void showImageList() {
        GridLayout wrapper = findViewById(R.id.gl_wrapper);
        wrapper.removeAllViews();
        // 根据ImageInfo创建ImageView，然后添加到页面中
        for (ImageInfo image : imageList) {
            ImageView imageView = new ImageView(this);
            // 设置显示的图片
            Bitmap bitmap = BitmapFactory.decodeFile(image.path);
            imageView.setImageBitmap(bitmap);
            // 设置缩放类型
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            // 设置宽高，先创建布局参数对象，通过参数对象设置ImageView的宽高,宽高单位为px，需要手动将dp转为px
            int width = Utils.dip2px(this, 110);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, width);
            imageView.setLayoutParams(params);
            // 设置内边距
            int padding = Utils.dip2px(this, 5);
            imageView.setPadding(padding, padding, padding, padding);

            // 设置点击事件
            imageView.setOnClickListener(v -> {
                sendMms(image.path);
            });

            wrapper.addView(imageView);
        }
    }

    /**
     * 访问相册
     * 也是通过 ContentProvider 去查询相册表中的内容
     * MediaStore - 类包含了所有多媒体的信息
     */
    @SuppressLint("Range")
    private void loadImageList() {
        Log.d("zhoutao", "loadImageList: ");

        // 要查询的列
        String[] columns = new String[]{
                MediaStore.Images.Media._ID,  // 编号
                MediaStore.Images.Media.TITLE,  // 标题
                MediaStore.Images.Media.SIZE,  // 文件大小
                MediaStore.Images.Media.DATA,  // 文件路径
        };

        // 查询
        Cursor cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns,
                // 小于100kb的图片
                "_size < 102400",
                null,
                "_size DESC"

        );

        Log.d("zhoutao", "cursor: " + cursor);

        if (cursor != null) {
            int count = 0;
            while (cursor.moveToNext() && count < 6) {


                ImageInfo image = new ImageInfo();
                image.id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID));
                image.name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.TITLE));
                image.size = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
                image.path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

                if(FileUtil.checkFileUri(this, image.path)){
                    imageList.add(image);
                    count++;
                }
                Log.d("zhoutao", image.toString());
            }
        }


        cursor.close();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSION_CODE_STORAGE && PermissionUtil.checkGrant(grantResults)) {
            // 读取图片
            loadImageList();
            // 加载图片
            showImageList();
        }
    }


    private void sendMms(String path) {
        Uri uri = Uri.parse(path);
        // android 7.0 之后需要通过FileProvider访问Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 通过FileProvider获取文件的Uri
            uri = FileProvider.getUriForFile(this, getString(R.string.file_provider), new File(path));
            Log.d("zhoutao", "FileProvider.uri: ");
        }

        // 发送彩信，开始一个Activity
        Intent intent = new Intent(Intent.ACTION_SEND);
        // 开启新的任务栈
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // Intent 的接收者，允许读取intent携带的URI数据
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        // 彩信发送的目标号码
        intent.putExtra("address", etPhone.getText().toString());
        // 彩信发送的标题
        intent.putExtra("subject", etTitle.getText().toString());
        // 彩信发送的内容
        intent.putExtra("sms_body", etMessage.getText().toString());
        // 彩信发送的附件
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        // 设置附件类型
        intent.setType("image/*");
        // 由于未指定打开哪个页面，所以系统会弹出选择窗口
        startActivity(intent);
        ToastHelper.show(this, "请选择短信的方式发送彩信");
    }
}